package com.easylinkin.linkappapi.inspection.controller;

import com.baomidou.mybatisplus.generator.config.IFileCreate;
import com.easylinkin.linkappapi.circuit.entity.RailGiveSystemAlarm;
import com.easylinkin.linkappapi.circuit.service.IRailCircuitGivealarmService;
import com.easylinkin.linkappapi.circuit.service.IRailGiveSystemAlarmService;
import com.easylinkin.linkappapi.circuit.vo.RailCircuitGivealarmVO;
import com.easylinkin.linkappapi.circuit.vo.RailGiveSystemAlarmVO;
import com.easylinkin.linkappapi.device.constant.DeviceConstant;
import com.easylinkin.linkappapi.device.entity.Device;
import com.easylinkin.linkappapi.device.entity.ElectricyRecords;
import com.easylinkin.linkappapi.device.entity.vo.ElectricyStatisticsVo;
import com.easylinkin.linkappapi.device.service.DeviceService;
import com.easylinkin.linkappapi.device.service.ElectricyRecordsService;
import com.easylinkin.linkappapi.inspection.service.IRailLinkappElectricFireRecordService;
import com.easylinkin.linkappapi.inspection.vo.RailLinkappElectricFireRecordVO;
import com.easylinkin.linkappapi.mechanical.entity.EquipmentLocation;
import com.easylinkin.linkappapi.mechanical.mapper.EquipmentLocationMapper;
import com.easylinkin.linkappapi.mechanical.vo.EquipmentLocationVo;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import io.github.classgraph.HasName;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import javax.annotation.Resource;
import java.util.*;

/** 用电安全大屏接口类
 * @author lyk
 * @date 2025/6/24 下午 5:41
 */
@RestController
@RequestMapping("/useElectric")
public class UseElectricStatisticsController {

    @Autowired
    private DeviceService deviceService;

    @Resource
    private LinkappUserContextProducer linkappUserContextProducer;
    @Autowired
    private EquipmentLocationMapper equipmentLocationMapper;

    @Autowired
    private IRailGiveSystemAlarmService railGiveSystemAlarmService;

    @Autowired
    private ElectricyRecordsService electricyRecordsService;

    @Autowired
    private IRailCircuitGivealarmService railCircuitGivealarmService;
    @Autowired
    private IRailLinkappElectricFireRecordService railLinkappElectricFireRecordService;
    /**
     * 用电设备数量统计(电表，电气火灾，断路器)
     * @return
     */
     @GetMapping(value = "/useEleDeviceStatistics")
     public RestMessage useEleDeviceStatistics(){
         String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
         //断路器
         Device dlq_dev = new Device();
         dlq_dev.setTenantId(tenantId);
         dlq_dev.setDeviceTypeName(DeviceConstant.RailwayDeviceType.CIRCUIT_BREAKER.getDescription());
         List<Device> dlq_data = deviceService.selectByTypeNameDevicesList(dlq_dev);
         //电气火灾
         Device dqhz_dev = new Device();
         dqhz_dev.setTenantId(tenantId);
         dqhz_dev.setDeviceTypeName(DeviceConstant.RailwayDeviceType.ELECTRIC_FIRE.getDescription());
         List<Device> qdhz_data = deviceService.selectByTypeNameDevicesList(dqhz_dev);
         //电表
         Device db_dev = new Device();
         db_dev.setTenantId(tenantId);
         db_dev.setDeviceTypeName(DeviceConstant.RailwayDeviceType.ELECTRIC_METER.getDescription());
         List<Device> db_data = deviceService.selectByTypeNameDevicesList(db_dev);
         int sum = dlq_data.size() + db_data.size() + qdhz_data.size();
         dlq_data.addAll(db_data);
         dlq_data.addAll(qdhz_data);
         int gjSum = 0;
         int lineUpSum = 0;
         for (Device dev:dlq_data){
             if (Integer.valueOf(1).equals(dev.getStatus())){
                 gjSum++;
             }
             if (Integer.valueOf(1).equals(dev.getOnlineState())){
                 lineUpSum++;
             }
         }
         Map<Object, Object> result = new HashMap<>();
         result.put("sum",sum);
         result.put("gjSum",gjSum);
         result.put("lineUpSum",lineUpSum);
         return RestBuilders.successBuilder().data(result).build();
     }

    /**
     * 用电安全大屏查找地图的用电设备，返回设备相关的数据
     */
    @GetMapping(value = "/geoMapUseEleDevice")
    public RestMessage geoMapUseEleDevice(){
        EquipmentLocationVo vo = new  EquipmentLocationVo();
        List<String> nameTypes = new ArrayList<>();
        nameTypes.add("电表");
        nameTypes.add("断路器");
        nameTypes.add("电气火灾");
        vo.setTypeNames(nameTypes);
        vo.setTenantId(linkappUserContextProducer.getNotNullCurrent().getTenantId());
        List<EquipmentLocation> equipmentLocations = equipmentLocationMapper.listPage(vo);
        return RestBuilders.successBuilder().data(equipmentLocations).build();
    }

    /**返回今日所有用电设备的告警记录
     * @return
     */
    @GetMapping(value = "/todayEleEquipmentAlarmList")
    public RestMessage todayEleEquipmentAlarmList(){
       List<RailGiveSystemAlarmVO>  list = railGiveSystemAlarmService.todayEleEquipmentAlarmList();
        return RestBuilders.successBuilder().data(list).build();
    }

    /**
     * 用电安全大屏左侧设备列表查询加详情统计接口
     * @return
     */
    @GetMapping(value = "/eleDeviceDetailsByList")
    public RestMessage eleDeviceDetailsByList() {
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        Device device = new Device();
        List<String> types = new ArrayList<>();
        types.add("电表");
        types.add("断路器");
        types.add("电气火灾");
        device.setDeviceTypeNames(types);
        device.setTenantId(tenantId);
        List<Device> devices = deviceService.selectByTypeNameDevicesList(device);
        List<Map<String, Object>> maps = new ArrayList<>();
        //1 电表  2 断路器 3 电气火灾
        Map<String, List<String>> transMapGroup = new HashMap<>();
        Map<String, Device> transMapDev = new HashMap<>();
        //设备分组
        for (Device dev : devices) {
            String keys = "";
            String code = dev.getCode();
            if (!StringUtils.isEmpty(dev.getDeviceTypeName())) {
                if (dev.getDeviceTypeName().equals("电表")) {
                    keys = "1";
                } else if (dev.getDeviceTypeName().equals("断路器")) {
                    keys = "2";
                } else if (dev.getDeviceTypeName().equals("电气火灾")) {
                    keys = "3";
                }
            }
            if (!StringUtils.isEmpty(keys) && !StringUtils.isEmpty(code)) {
                List<String> strings = transMapGroup.get(keys);
                if (Objects.isNull(strings)) {
                    strings = new ArrayList<>();
                    strings.add(code);
                } else {
                    strings.add(code);
                }
                transMapGroup.put(keys, strings);
            }
            transMapDev.put(dev.getCode(),dev);
        }
        //查询各个设备最新流水数据
        for (Map.Entry<String, List<String>> entry : transMapGroup.entrySet()) {
            String key = entry.getKey();
            List<String> value = entry.getValue();
            if (Objects.isNull(value)){
                continue;
            }
            if (value.size()==0){
                continue;
            }
            Map<String, Object> map = null;
            switch (key){
                case "1":
                    //最新电表流水
                    List<ElectricyRecords> electricyStatisticsVos = electricyRecordsService.codeByNewRecords(tenantId, value);
                    //加进数组
                    if (electricyStatisticsVos.size() == 0){
                        break;
                    }
                    for (ElectricyRecords records:electricyStatisticsVos){
                        String dev_code = records.getDeviceCode();
                        Device device1 = transMapDev.get(dev_code);
                        if (!Objects.isNull(device1)){
                            map = new HashMap<>();
                            map.put("deviceTypeName",device1.getDeviceTypeName());
                            map.put("device",device1.getName());
                            map.put("deviceCode",device1.getCode());
                            map.put("lastPushTime",device1.getLastPushTime());
                            map.put("onlineState",device1.getOnlineState());
                            map.put("records",records);
                            map.put("status", device1.getStatus());
                            maps.add(map);
                            transMapDev.remove(dev_code);
                        }
                    }
                    break;
                case "2":
                    //断路器
                    List<RailCircuitGivealarmVO> RailCircuitGivealarmVOs = railCircuitGivealarmService.codeByNewRecords(tenantId, value);
                    //加进数组
                    if (RailCircuitGivealarmVOs.size() == 0){
                        break;
                    }
                    for (RailCircuitGivealarmVO vos:RailCircuitGivealarmVOs){
                        String dev_code = vos.getDeviceCode();
                        Device device1 = transMapDev.get(dev_code);
                        if (!Objects.isNull(device1)) {
                            map = new HashMap<>();
                            map.put("deviceTypeName", device1.getDeviceTypeName());
                            map.put("device", device1.getName());
                            map.put("deviceCode", device1.getCode());
                            map.put("lastPushTime", device1.getLastPushTime());
                            map.put("onlineState", device1.getOnlineState());
                            map.put("electStatus",device1.getElectStatus());
                            map.put("records", vos);
                            map.put("status", device1.getStatus());
                            maps.add(map);
                            transMapDev.remove(dev_code);
                        }
                    }
                    break;
                case "3":
                    //电气火灾
                    List<RailLinkappElectricFireRecordVO>  RailLinkappElectricFireRecordVOs =  railLinkappElectricFireRecordService.codeByNewRecords(tenantId, value);
                    //加进数组
                    if (RailLinkappElectricFireRecordVOs.size() == 0){
                        break;
                    }
                    for (RailLinkappElectricFireRecordVO vos:RailLinkappElectricFireRecordVOs){
                        String dev_code = vos.getDeviceCode();
                        Device device1 = transMapDev.get(dev_code);
                        if (!Objects.isNull(device1)) {
                            map = new HashMap<>();
                            map.put("deviceTypeName", device1.getDeviceTypeName());
                            map.put("device", device1.getName());
                            map.put("deviceCode", device1.getCode());
                            map.put("lastPushTime", device1.getLastPushTime());
                            map.put("onlineState", device1.getOnlineState());
                            map.put("electStatus",device1.getElectStatus());
                            map.put("records", vos);
                            map.put("status", device1.getStatus());
                            maps.add(map);
                            transMapDev.remove(dev_code);
                        }
                    }
                    break;
                default:
                    break;
            }
        }

        for (Map.Entry<String,Device> entry:transMapDev.entrySet()){
            Map<String, Object> map = new HashMap<>();
            map.put("deviceTypeName", entry.getValue().getDeviceTypeName());
            map.put("device",  entry.getValue().getName());
            map.put("deviceCode",  entry.getValue().getCode());
            map.put("lastPushTime",  entry.getValue().getLastPushTime());
            map.put("onlineState",  entry.getValue().getOnlineState());
            map.put("electStatus", entry.getValue().getElectStatus());
            map.put("status",  entry.getValue().getStatus());
            maps.add(map);
        }
        return RestBuilders.successBuilder().data(maps).build();
    }

}
